import torch
from torch import Tensor
from torch.nn import Module


def test(model: Module, x: Tensor, y: Tensor):
    x = torch.transpose(x, 0, 1)
    len_by_batch = []
    for each_y in y:
        len_each = 0
        for each_y_item in each_y:
            if each_y_item >= 0:
                len_each = len_each + 1
        len_by_batch.append(len_each)
    inputs = torch.nn.utils.rnn.pack_padded_sequence(input=x, lengths=len_by_batch, enforce_sorted=False)
    target = y[:, 0:max(len_by_batch)]
    predict: Tensor = model(inputs, y.shape[0])
    predict = predict.reshape(predict.shape[0] * predict.shape[1], -1)
    target = target.reshape(target.shape[0] * target.shape[1])
    predict = predict[target >= 0]
    target = target[target >= 0]
    print(predict)
    _, predict_y_pos = torch.max(predict, dim=1)
    check_num = torch.sum(predict_y_pos.eq(target), dim=0)
    print('预测成功率：', check_num * 1.0 / target.shape[0])
